<template>
  <base-breadcrumb>
    <searchData ref="searchData" :search-data="searchArr" @search="search" />
    <a-card :bordered="false">
      <list-table
        ref="table"
        :loading="loading"
         :columns="columns"
         :start-index="0"
         :request="loadData2"
         :export-permission="{ select: 'crm_001_exp_02', all: 'crm_001_expall_03' }"
         :export-config="{ use: true, select: '投诉列表', all: '投诉列表',customColumns}"
        row-key="id"
      >
        <a-button  slot="prefix" v-btnPermission="'crm_001_add_01'" type="primary" icon="plus" @click="handleEdit(null, 1, true)"> 新增投诉 </a-button>
        <template slot="index" slot-scope="text, record, index">
          {{ index + 1 }}
        </template>
        <template slot="projectName" slot-scope="text, record">
          <div v-for="(ite, inx) in projectData" :key="inx">
            <div v-if="ite.id == record.projectId">
              {{ ite.name }}
            </div>
          </div>
        </template>

        <template slot="complaintConsult" slot-scope="text, record">
          <a class="base-btn" @click="getInfoShow(record)">{{ record.complaintConsult }}</a>
        </template>
        <div slot="operation" slot-scope="text, record">
          <MoreButton>
            <a v-btnPermission="'crm_001_loo_04'" @click="handleEdit(record, 3, true)">查看</a>
            <a v-if="record.status == 0 || record.status == 3" v-btnPermission="'crm_001_res_05'" @click="() => handleEdit(record, 2, true)">投诉响应</a>
            <a v-if="record.status == 0 || record.status == 1 || record.status == 3" v-btnPermission="'crm_001_rev_06'" @click="() => handleDel(record.id)">撤销</a>
            <approval-button v-if="record.status != 0" :id="record.id" v-btnPermission="'crm_001_app_07'" />
          </MoreButton>
        </div>
      </list-table>
    </a-card>
    <a-modal title="投诉借鉴" :visible="infoShow" style="width: 50%" cancel-text="关闭" @ok="infoShow = false" @cancel="cancelInfoShow">
      <s-table v-if="infoShow" ref="infotable" size="default" row-key="id" :columns="infoColumns" :data="loadData" :alert="true" show-size-changer show-quick-jumper show-pagination="auto" :scroll="{ y: 600 }">
        <template slot="status" slot-scope="text, record">
          <div>
            <span v-if="record.status == 0">待提交审核</span>
            <span v-if="record.status == 1">审核中</span>
            <span v-if="record.status == 2">待业主反馈</span>
            <span v-if="record.status == 3">审核不通过</span>
            <span v-if="record.status == 4">已闭合</span>
            <span v-if="record.status == 9">已撤销</span>
          </div>
        </template>
        <template slot="operator" slot-scope="text, record">
          <a class="base-btn" @click="handleEdit(record, 3)">详情</a>
        </template>
      </s-table>
      <template slot="footer">
        <a-button @click="cancelInfoShow"> 关闭 </a-button>
      </template>
    </a-modal>
  </base-breadcrumb>
</template>
<script>
// import { deviceListDel } from '@/api/material/acceptance/device'
import { getComplaintList, exportComplaint, getPCProjectList, customerComplaintCancel, queryComplaintTree } from '@/api/complaint'
// import Selector from '@/components/Select/Selector'
import { STable } from '@/components'
// import SelectProject from '@/components/Select/SelectProject' // 项目
// import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject' // 组织
import OrgTreeSelect from '@/components/OrgTreeSelect'

export default {
  name: 'a' + Date.now(),
  components: {
    STable
  },
  data: function () {
    return {
      loading: false,
      infoShow: false,

      pathName: this.$route.path,
      queryParam: {},
      infoQueryParam: {},
      pageNo: 1,
      pageSize: 10,
      totalSize: 0,
      customColumns:[],
      infoColumns: [
        {
          title: '项目名称',
          dataIndex: 'projectName'
        },
        {
          title: '投诉单编号',
          dataIndex: 'code'
        },
        {
          title: '投诉级别',
          dataIndex: 'level'
        },
        {
          title: '投诉时间',
          dataIndex: 'complaintTime'
        },
        {
          title: '状态',
          dataIndex: 'statusName'
        },
        {
          title: '操作',
          dataIndex: 'operator',
          width: 200,
          fixed: 'right',
          scopedSlots: { customRender: 'operator' }
        }
      ],
      searchArr: [
        {
          name: '投诉单编号',
          value: 'code',
          type: 'input'
        },
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // {
        //   name: '所属组织',
        //   valueKey: 'statisticsId',
        //   type: SelectCompanyAndProject
        // },
        // {
        //   name: '所属分公司',
        //   valueKey: 'branchComId',
        //   type: SelectSubCompany
        // },
        // {
        //   name: '项目名称',
        //   type: SelectProject,
        //   keyValue: 'branchComId',
        //   valueKey: 'projectId'
        // },
        {
          name: '业态',
          value: 'formats',
          type: 'input'
        },
        {
          name: '是否为重点项目',
          value: 'keyProject',
          type: 'select',
          data: [
            {
              value: '是',
              label: '是'
            },
            {
              value: '否',
              label: '否'
            }
          ]
        },
        {
          name: '施工阶段',
          type: 'select',
          value: 'constructionStage',
          data: [
            {
              value: '1',
              label: '施工准备阶段'
            },
            {
              value: '2',
              label: '地基基础阶段'
            },
            {
              value: '3',
              label: '主体结构阶段'
            },
            {
              value: '4',
              label: '装饰装修阶段'
            },
            {
              value: '5',
              label: '竣工收尾阶段'
            },
            {
              value: '6',
              label: '维保阶段'
            }
          ]
        },
        {
          name: '建设单位',
          value: 'constructionUnit',
          type: 'input'
        },
        {
          name: '投诉级别',
          value: 'level',
          type: 'select',
          data: [
            {
              value: '1',
              label: '一般投诉'
            },
            {
              value: '2',
              label: '严重投诉'
            },
            {
              value: '3',
              label: '紧急投诉'
            }
          ]
        },
        {
          name: '投诉类型',
          value: 'treeId',
          type: 'select',
          data: []
        },
        {
          name: '投诉时间',
          value: 'createTime',
          type: 'dateRange',
          attr: {
            rangeFormat: ['startTime', 'endTime']
          }
        },
        {
          name: '状态',
          value: 'statusList',
          type: 'selectMode',
          data: [
            {
              value: '0',
              label: '待提交审核'
            },
            {
              value: '1',
              label: '审核中'
            },
            {
              value: '2',
              label: '待业主反馈'
            },
            {
              value: '3',
              label: '审核不通过'
            },
            {
              value: '4',
              label: '已闭合'
            },
            {
              value: '9',
              label: '已撤销'
            }
          ]
        },
        {
          name: '处理次数',
          value: 'many',
          type: 'select',
          data: [
            {
              value: '0',
              label: '多次'
            },
            {
              value: '1',
              label: '一次'
            }
          ]
        },
        {
          name: '响应天数',
          value: 'responseDaysType',
          type: 'select',
          data: [
            {
              value: '1',
              label: '1-3天'
            },
            {
              value: '2',
              label: '3-5天'
            },
            {
              value: '3',
              label: '5-7天'
            },
            {
              value: '4',
              label: '7-9天'
            },
            {
              value: '5',
              label: '10天及以上'
            }
          ]
        }
      ],
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'index' },
          width: 70
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: 220
        },
        {
          title: '所属分公司',
          dataIndex: 'branchComName',
          width: 160
        },
        {
          title: '投诉单编号',
          dataIndex: 'code',
          width: 160
        },

        {
          title: '业态',
          dataIndex: 'formats',
          width: 160
        },
        {
          title: '是否为重点项目',
          dataIndex: 'keyProject',
          width: 160
        },
        {
          title: '施工阶段',
          dataIndex: 'constructionStage',
          width: 160
        },
        {
          title: '建设单位',
          dataIndex: 'constructionUnit',
          width: 160
        },
        {
          title: '投诉级别',
          dataIndex: 'level',
          width: 160
        },
        {
          title: '投诉类型',
          dataIndex: 'treeName',
          width: 160
        },
        {
          title: '投诉时间',
          dataIndex: 'complaintTime',
          width: 160
        },
        {
          title: '响应天数',
          dataIndex: 'responseDays',
          width: 160
        },
        {
          title: '处理次数',
          dataIndex: 'handleTimes',
          width: 160
        },
        {
          title: '投诉借鉴',
          dataIndex: 'complaintConsult',
          scopedSlots: { customRender: 'complaintConsult' },
          width: 160
        },
        {
          title: '状态',
          width: 160,
          dataIndex: 'statusName'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 200,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      sgOptions: [
        {
          value: '1',
          label: '施工准备阶段'
        },
        {
          value: '2',
          label: '地基基础阶段'
        },
        {
          value: '3',
          label: '主体结构阶段'
        },
        {
          value: '4',
          label: '装饰装修阶段'
        },
        {
          value: '5',
          label: '竣工收尾阶段'
        },
        {
          value: '6',
          label: '维保阶段'
        }
      ],
      selectedRowKeys: [],
      selectId: [],
      selectedRows: [],
      chooseData: 0,
      tableData: [],
      projectData: [],
      loadData2: (parameter) => {
          let that = this
          parameter.pageNum = parameter.pageNo;
          delete parameter.pageNo;
          this.loading = true;
          const requestParameters = Object.assign({}, parameter, { param: that.queryParam })
          return getComplaintList(requestParameters).then((res) => {
          let list = res.data?.list;
          this.loading = false;
          return { code: 200, data: list, totalSize: res.data?.total }
          })
        },
    }
  },
  created() {
    //  就是他的当前岗位层级，分别对应CO：公司级，BC：分公司级，PD：项目级
    if (this.$currentPost().code == 'CO') {
    }
    if (this.$currentPost().code == 'BC') {
      this.columns.splice(2, 1)
    }
    if (this.$currentPost().code == 'PD') {
      this.columns.splice(2, 1)
      this.columns.splice(3, 4)
    }
    this.customColumns = JSON.parse(JSON.stringify(this.columns));
    if(this.customColumns[0].dataIndex=='index'){
        this.customColumns.shift();
    }
    this.getCode()
    if (!this.$route.params || (this.$route.params instanceof Object && !Object.keys(this.$route.params)?.length)) {
      this.list()
    }
  },
  watch: {
    $route(to, from) {
      console.log(to)
      let params = to.params
      if (params) {
        try {
          console.log(params)
          from.path === '/complaint/statistics' && this.$refs.searchData?.form?.resetFields()
          this.$refs.searchData?.form?.setFieldsValue(params)
          this.$refs.searchData?.search()
        } catch (e) {
          //TODO handle the exception
        }
      }
    }
  },
  mounted: function () {
    let complaints = sessionStorage.getItem('complaints') ?? null
    complaints && this.getInfoShow(JSON.parse(complaints))
    if (this.$route.params) {
      let data = this.$route.params
      // this.$refs.searchData?.form?.resetFields()
      this.$refs.searchData.form.setFieldsValue(data)
      this.$refs.searchData?.search()
    }
    this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
    this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      this.list()
    })
  },
  beforeDestroy() {
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  methods: {
    cancelInfoShow() {
      this.infoShow = false
      sessionStorage.removeItem('complaints')
    },
    loadData(parameter) {
      const searchData = {
        pageSize: parameter.pageSize,
        pageNum: parameter.pageNo,
        param: this.infoQueryParam
      }
      console.log(searchData)
      searchData.param.createTime && delete searchData.param.createTime
      return getComplaintList(searchData).then((res) => {
        return { code: 200, data: res.data?.list, total: res.data?.total }
      })
    },
    getInfoShow(record) {
      if (record.complaintConsult <= 0) {
        return false
      } else {
        this.infoQueryParam = {
          statusList: ['2', '4'],
          infoId: record.infoId
        }
        this.infoShow = true
        sessionStorage.setItem('complaints', JSON.stringify(record))
      }
    },
    getCode() {
      queryComplaintTree().then((res) => {
        const data = []
        res.data[0].children.map((item) => {
          item.children.map((ite) => {
            data.push({ label: ite.name, value: ite.id })
          })
        })
        this.searchArr[7].data = data
      })
    },
    exportSelect: function () {
      if (this.selectedRowKeys.length > 0) {
        this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
      } else {
        this.$message.warning('请选择需要导出的数据')
      }
    },
    exportAll: function () {
      if (this.totalSize) {
        this.pageNo = 1
        this.list(false, this.$refs.exportAll.setDataAndGenerate)
      } else {
        this.$message.warning('没有可导出的数据')
      }
    },
    list(callback) {

    },
    search(val) {
      this.queryParam = { ...val }
      this.$refs.table.refresh()
    },
    handleDel(id) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确定是否撤销投诉？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return customerComplaintCancel({ id: id })
            .then((res) => {
              that.$message.success('撤销成功！')
              that.list()
              that.$refs.table.refresh(true)
            })
            .catch((err) => {
              console.log(err)
            })
        }
      })
    },

    handleEdit(record, state, flag) {
      if (flag) {
        sessionStorage.removeItem('complaints')
      }
      this.infoShow = false
      this.$router.push({
        name: 'AddComplaint',
        query: {
          id: (record && record.id) || '',
          state: state
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-modal {
  width: 900px !important;
}
</style>
